package com.thinkwide.data.util;

import com.thinkwide.data.core.MFString;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 工具类-驼峰和下划线的转换
 *
 * @author andyzhang
 */
public class CaseUtils {

    private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");

    /**
     * 下划线命名转驼峰命名
     *
     * @param value
     * @return
     */
    public static String underscoreToCamel(String value) {
        String[] ss = value.split("_");
        if (ss.length == 1) {
            return value;
        }

        StringBuffer sb = new StringBuffer();
        sb.append(ss[0]);
        for (int i = 1; i < ss.length; i++) {
            sb.append(upperFirstCase(ss[i]));
        }

        return sb.toString();
    }

    /**
     * 驼峰 转下划线
     *
     * @param value
     * @return
     */
    public static String camelToUnderscore(String value) {
        if (MFString.isNullOrEmpty(value)) {
            return value;
        }

        value = lowerFirstCase(value);

        Matcher matcher = HUMP_PATTERN.matcher(value);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 对象属性转字段名
     *
     * @param value
     * @return
     */
    public static String propToField(String value) {

        return camelToUnderscore(value);
    }

    /**
     * 对象属性转字段名
     *
     * @param value
     * @return
     */
    public static String classToTable(String value) {

        return camelToUnderscore(value);
    }

    /**
     * 对象属性转字段名
     *
     * @param value
     * @return
     */
    public static String tableToClass(String value) {

        return upperFirstCase(underscoreToCamel(value));
    }

    /**
     * 对象属性转字段名
     *
     * @param value
     * @return
     */
    public static String fieldToProp(String value) {

        return underscoreToCamel(value);
    }


    /**
     * 首字母 转小写
     *
     * @param str
     * @return
     */
    public static String lowerFirstCase(String str) {
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    /**
     * 首字母 转大写
     *
     * @param str
     * @return
     */
    public static String upperFirstCase(String str) {
        char[] chars = str.toCharArray();
        chars[0] -= 32;
        return String.valueOf(chars);
    }


}
